package durst.action;

import java.sql.SQLException;

import net.sourceforge.stripes.action.RedirectResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.validation.SimpleError;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidationErrors;
import net.sourceforge.stripes.validation.ValidationMethod;
import durst.action.account.CalendarActionBean;
import durst.data.Account;
import durst.data.dao.DaoFactory;
import durst.data.dao.impl.AccountDao;

public class LoginActionBean extends CalendarBasicAction {
	private Account validatedAccount;

	@Validate(required = true, on = "login", minlength = 6, maxlength = 20, mask="\\w+")
	private String username;

	@Validate(required = true, on = "login", minlength = 6, maxlength = 32)
	private String password;

	@SuppressWarnings("unchecked")
	@ValidationMethod(on = "login")
	public void validateUser(ValidationErrors errors) throws SQLException {
		AccountDao<Account, Integer> dao = (AccountDao<Account, Integer>) DaoFactory
				.getInstance().createDao(Account.class);

		Account acc = dao.queryByUsername(username);

		if (acc == null || !acc.validatePassword(password))
			errors.add("username", new SimpleError("No user exists for those credentials"));
		else
			validatedAccount = acc;
		
		if (errors.size() > 0)
			context.setAccount(null);
	}

	public Resolution login() {
		context.setAccount(validatedAccount);
		return new RedirectResolution(CalendarActionBean.class);
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
}
